package bitmap.demo.service.impl;

import bitmap.demo.common.CommonConstant;
import bitmap.demo.common.CommonResponse;
import bitmap.demo.service.ITestService;
import bitmap.demo.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Service("testService")
public class TestServiceImpl implements ITestService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
public List<Integer> getPushData() {
    List<Integer> res = new ArrayList<>(366);
    // 没有数据就先造数据
    genTestData();
    int days = getDays();
    for(long i=0;i<days;i++){
        //每次直接读取一个字节的String
        String str = redisUtils.getStr(CommonConstant.KEY, i, i);
        if (str == null || str.length() < 1) {
            break;
        }
        //将String的第一个char转为int类型
        res.add((int)str.charAt(0));
    }
    return res;
}

    @Override
public void genTestData() {
    if(redisUtils.isExist(CommonConstant.KEY)){
        return;
    }
    // 获取当前年的总天数
    int days = getDays();
    for (int i = 0; i < days; i++) {
        int random = ThreadLocalRandom.current().nextInt(64);
        String binaryString = Integer.toBinaryString(random);
        if (binaryString.length() < 8) {
            if(binaryString.length() == 0){binaryString = "00000000";}
            else if(binaryString.length() == 1){binaryString = "0000000"+binaryString;}
            else if(binaryString.length() == 2){binaryString = "000000"+binaryString;}
            else if(binaryString.length() == 3){binaryString = "00000"+binaryString;}
            else if(binaryString.length() == 4){binaryString = "0000"+binaryString;}
            else if(binaryString.length() == 5){binaryString = "000"+binaryString;}
            else if(binaryString.length() == 6){binaryString = "00"+binaryString;}
            else if(binaryString.length() == 7){binaryString = "0"+binaryString;}
        }
        char[] chars = binaryString.toCharArray();
        for (int j = 0; j < chars.length; j++) {
            redisUtils.setBit(CommonConstant.KEY,i*8+j,chars[j]);
        }
    }
}



/**
 * 获取当前年的总天数
 * @return days 总天数
 */
private int getDays(){
    Calendar calOne = Calendar.getInstance();
    int year = calOne.get(Calendar.YEAR);
    System.out.println(year);
    Calendar calTwo = new GregorianCalendar(year, 11, 31);
    return calTwo.get(Calendar.DAY_OF_YEAR);
}
}
